<template>
	<xn-form-container
		:title="formData.id ? '编辑领取记录' : '增加领取记录'"
		:width="700"
		v-model:open="open"
		:destroy-on-close="true"
		@close="onClose"
	>
		<a-form ref="formRef" :model="formData" :rules="formRules" layout="vertical" allow-clear>
			<a-form-item label="请选择资产类别：" name="commodityCode">
				<a-select v-model:value="formData.commodityCode" @change="changeCommodityName">
					<a-select-option v-for="option in commodityList" :key="option.code" :value="option.code" :label="option.name">
						{{ option.name }}
					</a-select-option>
				</a-select>
			</a-form-item>
			<a-form-item v-show="visible" label="办公用品类型" name="officeSupplie">
				<a-select
					v-model:value="formData.officeSupplies"
					placeholder="请选择案件状态"
					:options="OfficeSupplies"
					allowClear
				/>
			</a-form-item>
			<a-form-item label="条形码：" name="barcode">
				<a-input v-model:value="formData.barcode" placeholder="请输入条形码" allow-clear />
			</a-form-item>
			<a-form-item label="商品类型：" name="type">
				<a-select v-model:value="formData.type" placeholder="请选择类型" :options="purchaseTypeList" />
			</a-form-item>
			<a-form-item label="领取数量：" name="quantity">
				<a-input v-model:value="formData.quantity" placeholder="请输入领取数量" allow-clear />
			</a-form-item>
			<a-form-item label="领取用途：" name="purpose">
				<a-input v-model:value="formData.purpose" placeholder="请输入领取用途" allow-clear />
			</a-form-item>
			<a-form-item label="领取人：" name="collectedName">
				<a-input v-model:value="formData.collectedName" placeholder="请输入领取人" allow-clear />
			</a-form-item>
			<a-form-item label="领取人部门：" name="collectedDept">
				<a-tree-select
					v-model:value="formData.collectedDept"
					class="xn-wd"
					:dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
					placeholder="请选择组织"
					allow-clear
					tree-default-expand-all
					:tree-data="treeData"
					:tree-default-expanded-keys="treeDefaultExpandedKeys"
					:field-names="{
						children: 'children',
						label: 'name',
						value: 'id'
					}"
				></a-tree-select>
			</a-form-item>
			<a-form-item label="备注：" name="remark">
				<a-input v-model:value="formData.remark" placeholder="请输入备注" allow-clear />
			</a-form-item>
			<a-form-item label="上传商品照片">
				<div>
					<!-- 使用 antd 的 Upload 组件 -->
					<a-upload
						:before-upload="beforeUpload"
						:show-upload-list="false"
						@change="handleChange"
					>
						<!-- 自定义上传按钮 -->
						<a-button>
							<template #icon><upload-outlined /></template>
							点击上传图片
						</a-button>
					</a-upload>

					<!-- 图片预览区域 -->
					<div v-if="formData.commodityImg" class="image-preview">
						<img :src="formData.commodityImg" alt="preview" style="max-width: 300px;" />
					</div>
				</div>
			</a-form-item>
			<a-form-item label="上传签名">
				<div>
					<!-- 使用 antd 的 Upload 组件 -->
					<a-upload
						:before-upload="beforeUpload"
						:show-upload-list="false"
						@change="handleChanges"
					>
						<!-- 自定义上传按钮 -->
						<a-button>
							<template #icon><upload-outlined /></template>
							点击上传图片
						</a-button>
					</a-upload>

					<!-- 图片预览区域 -->
					<div v-if="formData.signatureImg" class="image-preview">
						<img :src="formData.signatureImg" alt="preview" style="max-width: 300px;" />
					</div>
				</div>
			</a-form-item>
		</a-form>
		<template #footer>
			<a-button style="margin-right: 8px" @click="onClose">关闭</a-button>
			<a-button type="primary" @click="onSubmit" :loading="submitLoading">保存</a-button>
		</template>
	</xn-form-container>
</template>

<script setup name="amsItemPickupRecordForm">
	import { cloneDeep } from 'lodash-es'
	import { required } from '@/utils/formRules'
	import amsItemPickupRecordApi from '@/api/ams/pickUp/amsItemPickupRecordApi'
	import amsCommodityInfoApi from '@/api/ams/commodity/amsCommodityInfoApi'
	import bizUserApi from '@/api/biz/bizUserApi'
	import {message} from "ant-design-vue";
	import fileApi from "@/api/tjzy/file/fileApi";
	import tool from "@/utils/tool";
	// 抽屉状态
	const open = ref(false)
	const emit = defineEmits({ successful: null })
	const formRef = ref()
	const treeData = ref([])
	const purchaseTypeList = ref([
		{
			value: 1,
			label: '购买'
		},
		{
			value: 2,
			label: '租赁'
		}
	])
	// 表单数据
	const formData = ref({
		id: undefined,
		commodityCode: undefined,
		barcode: undefined,
		quantity: undefined,
		purpose: undefined,
		collectedName: undefined,
		collectedDept: undefined,
		collectedDeptName: undefined,
		remark: undefined,
		commodityImg: undefined,
		signatureImg: undefined,
		officeSupplies: undefined,
		type: undefined,
	})
	const submitLoading = ref(false)
	const commodityList = ref([])
	const treeDefaultExpandedKeys = ref([])
	const visible = ref(false)

	// 打开抽屉
	const onOpen = (record) => {
		open.value = true
		if (record) {
			let recordData = cloneDeep(record)
			formData.value = Object.assign({}, recordData)
		}
	}
	// 关闭抽屉
	const onClose = () => {
		formRef.value.resetFields()
		formData.value = {}
		open.value = false
	}
	const OfficeSupplies = tool.dictList('Office_supplies')
	// 默认要校验的
	const formRules = {
		commodityCode: [required('请选择商品类别')],
		barcode: [required('请输入条形码')],
		quantity: [required('请输入领取数量')],
		purpose: [required('请输入领取目的')],
		collectedName: [required('请输入领取人姓名')],
		collectedDept: [required('请选择领取人部门')],
		remark: [required('请输入备注')]
	}
	// 验证并提交数据
	const onSubmit = () => {
		formRef.value
			.validate()
			.then(() => {
				submitLoading.value = true
				const formDataParam = cloneDeep(formData.value)
				console.log('----')
				console.log(formDataParam)

				amsItemPickupRecordApi
					.amsItemPickupRecordSubmitForm(formDataParam, formDataParam.id)
					.then(() => {
						onClose()
						emit('successful')
					})
					.finally(() => {
						submitLoading.value = false
					})
			})
			.catch(() => {})
	}

	// 在文件上传之前检查文件类型是否为图片
	const beforeUpload = (file) => {
		const isImage = file.type.startsWith('image/');
		if (!isImage) {
			message.error('只能上传图片格式!');
		}
		return isImage;
	};
	// 处理上传状态改变的逻辑
	const handleChange = (info) => {
		// 获取文件对象
		const file = info.file.originFileObj;
		// 构建 FormData 对象
		const formDataimg = new FormData();
		formDataimg.append('file', file);
		// 调用自定义的上传方法
		fileApi.upload(formDataimg).then((res)=>{
			//imageUrl.value = 'https://s3.cn-north-1.jdcloud-oss.com/loan-repayment-img/'+res
			formData.value.commodityImg = 'https://s3.cn-north-1.jdcloud-oss.com/loan-repayment-img/'+res
		})


	};
	const changeCommodityName = (val) => {
		if (val == 'WORK_USE') {
			visible.value = true
		} else {
			visible.value = false
			formData.value.officeSupplies = undefined
		}
	}

	const handleChanges = (info) => {
		// 获取文件对象
		const file = info.file.originFileObj;
		// 构建 FormData 对象
		const formDataimg1 = new FormData();
		formDataimg1.append('file', file);
		// 调用自定义的上传方法
		fileApi.upload(formDataimg1).then((res)=>{
			//imageUrl.value = 'https://s3.cn-north-1.jdcloud-oss.com/loan-repayment-img/'+res
			formData.value.signatureImg = 'https://s3.cn-north-1.jdcloud-oss.com/loan-repayment-img/'+res
		})

	};

	// 抛出函数
	defineExpose({
		onOpen
	})
	onMounted(() => {
		// 获取项目列表
		amsCommodityInfoApi.amsCommodityList().then((res) => {
			commodityList.value = res
		})
		bizUserApi.userOrgTreeSelector().then((res) => {
			if (res !== null) {
				treeData.value = res
				// 默认展开2级
				treeData.value.forEach((item) => {
					// 因为0的顶级
					if (item.parentId === '0') {
						treeDefaultExpandedKeys.value.push(item.id)
						// 取到下级ID
						if (item.children) {
							item.children.forEach((items) => {
								treeDefaultExpandedKeys.value.push(items.id)
							})
						}
					}
				})
			}
		})
	})
</script>
